package task

import (
	"fmt"
	"os"

	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
)

type BatchRenamer struct {
	BasicTask

	mFileInfos []*model.ModifiedFileInfo
}

func (task *BatchRenamer) GetLabel() string {
	return fmt.Sprintf("重命名%v项", len(task.mFileInfos))
}

func (task *BatchRenamer) start() {
	task.BasicTask.start()
	defer task.BasicTask.finish()

	task.batchRename()
}

func (task *BatchRenamer) batchRename() {
	log.Debug("batch renamer rename start")

	for i, item := range task.mFileInfos {
		if !task.isRunning() {
			return
		}

		oldPath := item.Old.GetPath()
		newPath := item.New.GetPath()

		// 源文件或目录不存在
		if !util.PathExists(oldPath) {
			continue
		}

		// 目标路径下已存在
		if util.PathExists(newPath) {
			// 冲突时重命名
			var err error
			newPath, err = util.ResolveFilenameConflict(newPath)
			if err != nil {
				task.fail(err)
				return
			}
		}

		// 移动文件或目录
		err := os.Rename(oldPath, newPath)
		if err != nil {
			task.fail(err)
			return
		}

		task.percentage = float64(i+1) / float64(len(task.mFileInfos))
		task.progress = fmt.Sprintf("%.2f%%, %v/%v, 重命名中", task.percentage*100, i+1, len(task.mFileInfos))
	}

	log.Debug("batch renamer rename end")
}

func NewBatchRenamer(mFileInfos []*model.ModifiedFileInfo) *BatchRenamer {
	task := &BatchRenamer{
		BasicTask:  newBasicTask("batch renamer"),
		mFileInfos: mFileInfos,
	}

	return task
}
